package com.yimi.yinhepda.views.unload_module.UnBlocking;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.pda.ym.base.BaseTitleActivity;
import com.pda.ym.base.CommonViewHolder;
import com.pda.ym.base.MultiTypeSupport;
import com.pda.ym.callbacks.UICallBack;
import com.pda.ym.net.NetRequest;
import com.pda.ym.utils.CarNoSelectDialog;
import com.pda.ym.utils.Constants;
import com.pda.ym.utils.SoundVibratorManager;
import com.pda.ym.utils.StringUtils;
import com.yimi.yinhepda.R;
import com.yimi.yinhepda.adapter.RecycleAdapter.UnBlockingNewAdapter;
import com.yimi.yinhepda.adapter.SpinnerAdapter;
import com.pda.ym.utils.ProvinceEnum;
import com.yimi.yinhepda.entity.bean.SealOrUnsealTaskEntity;
import com.yimi.yinhepda.entity.request.SealOrUnsealTaskRequest;
import com.yimi.yinhepda.entity.response.QuerySealOrUnsealTaskResponse;
import com.yimi.yinhepda.event.CreateStowagesEvent;
import com.yimi.yinhepda.utils.Common;
import com.yimi.yinhepda.views.createPackage_module.CreateDeptSelectActivity;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 融合：解封任务界面
 */
public class UnBlockingActivity extends BaseTitleActivity implements AdapterView.OnItemSelectedListener,
        CommonViewHolder.onItemCommonClickListener, TextWatcher {
    /**
     * 任务列表
     */
    private RecyclerView rvRightView;
    /**
     * 返回按钮
     */
    private Button btnBack;
    /**
     * 上一站布局
     */
    private LinearLayout llDept;
    /**
     * 解封详情
     */
    private Button btnDetail;
    /**
     * 配载单号名
     */
    private TextView tvStowageNoName;
    /**
     * 路线选择spinnner
     */
    private SpinnerAdapter<String> adapterLineType, adapterProvinceType;
    /**
     * 路线数据集合
     */
    private List<String> lineTypelist = new ArrayList<>();
    /**
     * 路线数据集合
     */
    private List<String> provinceTypelist = new ArrayList<>();
    /**
     * 部门编码
     */
    private String deptCode;
    /**
     * 部门名称
     */
    private String deptName;
    /**
     * 数据列表适配器
     */
    private UnBlockingNewAdapter mRightAdapter;
    /**
     * 列表数据
     */
    private List<SealOrUnsealTaskEntity> dataList = new ArrayList<>();
    /**
     * 临时转换的车牌号
     */
    private String mTempCarNo = "";

    public static Handler handler;
    private SealOrUnsealTaskEntity selectSealCarEntity;
    /**
     * 支持多种item
     */
    private MultiTypeSupport<SealOrUnsealTaskEntity> mMltiTypeSupport = new MultiTypeSupport() {

        @Override
        public int getLayoutId(Object item, int position) {
            if (position == 0) {
                return R.layout.view_search_laod_task;
            } else {
                return R.layout.adapter_unblocking_item_new;
            }
        }
    };

    @SuppressLint("HandlerLeak")
    private void setHandler() {
        handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                finish();
            }
        };
    }

    public UnBlockingActivity() {
        super(true);
    }

    @Override
    public int setContentViewId() {
        return R.layout.activity_un_blocking_new;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        rvRightView = findViewById(R.id.rv_right_view);
        btnBack = findViewById(R.id.create_unblocking_back);
        btnDetail = findViewById(R.id.btn_unblocking_detail);
        llDept = findViewById(R.id.ll_dept);
        tvStowageNoName = findViewById(R.id.tv_stowageNo_name);

        lineTypelist.addAll(Arrays.asList(getResources().getStringArray(R.array.line_type)));
        adapterLineType = new SpinnerAdapter<String>(this, R.layout.simple_spinner_item, lineTypelist);

        dataList.add(new SealOrUnsealTaskEntity());
        loadUIAdapter();

        btnBack.setOnClickListener(this);
        btnDetail.setOnClickListener(this);

        setHandler();

        if (!EventBus.getDefault().isRegistered(this)) {
            //注册事件
            EventBus.getDefault().register(this);
        }

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    private void loadUIAdapter() {
        if (mRightAdapter == null) {
            mRightAdapter = new UnBlockingNewAdapter(this, dataList, this, mMltiTypeSupport, this);
            rvRightView.setLayoutManager(new LinearLayoutManager(this));
            rvRightView.setAdapter(mRightAdapter);
        } else {
            mRightAdapter.notifyDataSetChanged();
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_selectNextDept:
                Intent intent = new Intent(this, CreateDeptSelectActivity.class);
                intent.putExtra("currentDept", sharedPreferUtil.getDeptCode());
                intent.putExtra("inputType", 2);
                startActivityForResult(intent, 0);
                break;
            case R.id.create_unblocking_back:
                finish();
                break;
            case R.id.btn_unblocking_detail:
                if (selectSealCarEntity == null || !selectSealCarEntity.isCheck()) {
                    showToast("请选择一条数据解封");
                    SoundVibratorManager.playSound(2);
                    return;
                }
                toScanBlockActivity();
                break;
            case R.id.btn_carPlate:
                CarNoSelectDialog.showCarPlateDialog(this, new CarNoSelectDialog.CarNoSelectListener() {
                    @Override
                    public void onclick(String carPlate) {
                        mRightAdapter.getBtnCarPlate().setText(carPlate);
                    }
                });
                break;
            case R.id.btn_down:

                String selectDept = mRightAdapter.getBtnSelectNextDept().getText().toString();
                String carNo = mRightAdapter.getEtCarNo().getText().toString();
                if ("".equals(carNo) && "".equals(selectDept)) {
                    showToast("请输入车牌号或上一站");
                    SoundVibratorManager.playSound(2);
                    return;
                }
                getUnBlockingData(null);
                break;
            default:
                break;
        }
    }

    @Override
    protected void handleBarCode(String result) {
        if (result == null) {
            SoundVibratorManager.playSound(2);
            showToast("条码扫描失败");
        } else {
            String palletName = StringUtils.getPalletName(result);
            if (!"".equals(palletName)) {
                mRightAdapter.getEtCarNo().setText(result.substring(3));
                mRightAdapter.getBtnCarPlate().setText(palletName);
                getUnBlockingData(null);
            } else {
                getUnBlockingData(result);
            }
        }
    }

    private void toScanBlockActivity() {
        Intent intent = new Intent(UnBlockingActivity.this, ScanBlockingActivity.class);
        intent.putExtra("task", selectSealCarEntity);
        startActivity(intent);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            deptCode = data.getStringExtra("deptCode");
            deptName = data.getStringExtra("deptName");
            //选择的上一站
            mRightAdapter.getBtnSelectNextDept().setText(deptName);
            mRightAdapter.getBtnSelectNextDept().setTag(deptCode);
        }
    }

    @Override
    public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {

        switch (adapterView.getId()) {
            case R.id.tv_line_type:
                if (i == 0) {
                    llDept.setVisibility(View.VISIBLE);
                    tvStowageNoName.setText("任务号");
                } else {
                    llDept.setVisibility(View.GONE);
                    tvStowageNoName.setText("配载单号");
                }
                break;
            default:
                break;
        }
    }

    @Override
    public void onNothingSelected(AdapterView<?> adapterView) {

    }

    @Override
    public void onItemClickListener(int position) {
        if (position == RecyclerView.NO_POSITION) {
            return;
        }
        selectSealCarEntity = dataList.get(position);
        if (!selectSealCarEntity.isCheck()) {
            for (SealOrUnsealTaskEntity entity : dataList) {
                entity.setCheck(false);
            }
            selectSealCarEntity.setCheck(true);
        } else {
            selectSealCarEntity.setCheck(false);
        }
        loadUIAdapter();
    }

    @Override
    public void onItemLongClickListener(int position) {

    }

    /**
     * 获取待解封数据
     */
    public void getUnBlockingData(String taskNo) {

        SealOrUnsealTaskRequest entity = new SealOrUnsealTaskRequest();
        if (taskNo == null) {
            String carNo = mRightAdapter.getEtCarNo().getText().toString().toUpperCase();
            if (!"".equals(carNo)) {
                entity.setCarNo(mRightAdapter.getBtnCarPlate().getText().toString() + carNo);
            }
            if (mRightAdapter.getBtnSelectNextDept().getTag() != null) {
                entity.setDestDeptCode(mRightAdapter.getBtnSelectNextDept().getTag().toString());
            }
        } else {
            entity.setTaskNo(taskNo);
        }

        entity.setSrcDeptCode(sharedPreferUtil.getDeptCode());
        entity.setOperTypeCode(2);

        showPgDlg("正在加载...");

        new NetRequest().setMethod(NetRequest.Method.POST_STRING)
                .setUrl(Constants.URL_V2_QUERY_SEAL_OR_UNSEAL_TASK)
                .setRequestObject(entity)
                .setResponsClazz(QuerySealOrUnsealTaskResponse.class)
                .setConnTimeOut(10 * 1000)
                .execute(new UICallBack() {
                    @Override
                    public void onError(String msg) {
                        dismissPgDlg();
                        showToast(msg);
                        SoundVibratorManager.playSound(2);
                    }

                    @Override
                    public void onSuccess(Object obj) {
                        dismissPgDlg();
                        QuerySealOrUnsealTaskResponse response = (QuerySealOrUnsealTaskResponse) obj;

                        if (response != null && response.getData() != null && !response.getData().isEmpty()) {
                            dataList.clear();
                            dataList.add(new SealOrUnsealTaskEntity());
                            dataList.addAll(response.getData());
                            loadUIAdapter();
                            SoundVibratorManager.playSound(1);
                        } else {
                            dataList.clear();
                            dataList.add(new SealOrUnsealTaskEntity());
                            loadUIAdapter();
                            showToast("无解封任务");
                            SoundVibratorManager.playSound(2);
                        }
                    }
                });
    }

    @Override
    public String getPageName() {
        return "解封任务";
    }

    @Override
    public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

    }

    @Override
    public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

    }

    @Override
    public void afterTextChanged(Editable editable) {
        //车牌号英文字母转换成大写
        String carNo = mRightAdapter.getEtCarNo().getText().toString().toUpperCase();
        if (!carNo.equalsIgnoreCase(mTempCarNo)) {
            mTempCarNo = carNo;
            mRightAdapter.getEtCarNo().setText(carNo);
            mRightAdapter.getEtCarNo().setSelection(carNo.length());
        }
    }

    @Override
    public boolean showBack() {
        return false;
    }

    @Override
    public void setBack() {

    }

    @NotNull
    @Override
    public String setTitle() {
        return getPageName();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMainEventBus(CreateStowagesEvent event) {
        if (event.getFromActivity() == 5) {
            getUnBlockingData(null);
        }
    }

}
